package com.example.emailcraft.interceptor;

import com.example.emailcraft.entity.dto.CurrentUser;

public class CurrentUserHolder {
    // 使用静态 final 保证全局唯一性
    private static final ThreadLocal<CurrentUser> context = new ThreadLocal<>();

    // 私有构造器防止实例化
    private CurrentUserHolder() {
        throw new UnsupportedOperationException("Utility class cannot be instantiated");
    }

    /**
     * 设置当前用户（禁止覆盖或设置null）
     * @param user 必须为非空且已认证的用户对象
     */
    public static void set(CurrentUser user) {
        if (user == null) {
            throw new IllegalArgumentException("CurrentUser cannot be null");
        }
        if (context.get() != null) {
            throw new IllegalStateException("CurrentUser already set. Clear before resetting.");
        }
        context.set(user);
    }

    /**
     * 获取当前用户（可能为null）
     */
    public static CurrentUser get() {
        return context.get();
    }

    /**
     * 安全获取当前用户（非空保障）
     * @throws IllegalStateException 用户未设置时抛出
     */
    public static CurrentUser getRequired() {
        CurrentUser user = context.get();
        if (user == null) {
            throw new IllegalStateException("No current user in context");
        }
        return user;
    }

    /**
     * 强制清理当前用户上下文（必须由过滤器调用）
     */
    public static void clear() {
        context.remove();
    }
}
